#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/5/15 11:12
# @Author  : CHEN Wang
# @Site    :
# @File    : my_excel.py
# @Software: PyCharm

"""
脚本说明: 对redis数据库的连接，及各种操作
"""


from quant_researcher.quant.project_tool.logger.my_logger import LOG
import redis
from redis.sentinel import Sentinel


def get_sentinel(sentinel_url):
    sentinels = [x.split(':', maxsplit=1) for x in sentinel_url.split('|')]
    sentinels = [(x[0], x[1]) for x in sentinels]
    LOG.warning(f'哨兵們：{sentinels}')
    return Sentinel(sentinels=sentinels)


def get_master(sentinel_url, password, db, master):
    if master is None:
        raise ValueError(f'sentinel模式下，master不能為None')
    sentinel = get_sentinel(sentinel_url)

    # 額外信息
    # master_info = sentinel.discover_master(master)
    # print('master_info:', master_info)
    # slave_info = sentinel.discover_master(master)
    # print('slave_info:', slave_info)

    LOG.warning(f'获取主服务器进行写入，master={master}，密碼=***，數據庫={db}')
    master = sentinel.master_for(
        master, socket_timeout=0.5, password=password, db=db
    )
    return master


def get_slave(sentinel_url, password, db, master):
    if master is None:
        raise ValueError(f'sentinel模式下，master不能為None')
    sentinel = get_sentinel(sentinel_url)

    # 获取从服务器进行读取（默认是 round-roubin，随机从多个 slave 中读取数据）
    LOG.warning(f'获取从服务器进行读取，master={master}，密碼=***，數據庫={db}')
    slave = sentinel.slave_for(
        master,
        socket_timeout=0.5,
        password=password,
        db=db,
        decode_responses=True
    )
    return slave


def get_operator(url, password, db):
    host, port = url.split(':')
    LOG.warning(f'嘗試獲取 redis operator，host={host}，port={port}，db={db}')
    pool = redis.ConnectionPool(
        host=host, port=port, password=password, db=db, decode_responses=True
    )
    r = redis.Redis(connection_pool=pool)
    return r